/**
 * 
 */
package leetCode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhong
 *
 */
public class RemoveComments {
	public List<String> removeComments(String[] source) {
		int i = 0;
		int n = source.length;
		List<String> reStrings = new ArrayList<String>();
		while (i < n) {
			String shouldRt = source[i];
			int blockStartIndex = source[i].indexOf("/*");
			int lineIndex = source[i].indexOf("//");
			boolean blockStart = blockStartIndex != -1;
			boolean lineStart = lineIndex != -1;
			if (blockStart && lineStart) {
				if (blockStartIndex < lineIndex) {
					lineStart = false;
				} else {
					blockStart = false;
				}
			}
			if (blockStart) {// 如果有块注释
				int j = i;
				int blockEndIndex = source[j].indexOf("*/");
				while (blockEndIndex != -1 && blockEndIndex < blockStartIndex + 2) {// 如果是/*/或者*/出现在/*前面，则要继续找
					blockEndIndex = source[j].indexOf("*/", blockEndIndex + 2);
				}
				while (blockEndIndex == -1) {
					j++;
					blockEndIndex = source[j].indexOf("*/");
				}
				shouldRt = source[i].substring(0, blockStartIndex)
						+ source[j].substring(blockEndIndex + 2, source[j].length());

				i = j;
				source[i] = shouldRt;// 不能直接放到结果中
				continue;
			} else if (lineStart) {
				if (lineIndex != -1) {
					shouldRt = source[i].substring(0, lineIndex);
				}
			}
			i++;
			if (!shouldRt.isEmpty())
				reStrings.add(shouldRt);
		}
		return reStrings;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String[] source = { "a/*/b//*c", "blank", "d/*/e*//f" };
		System.out.println(new RemoveComments().removeComments(source));
	}

}
